﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Linq.Expressions;
using Extentions;
using Microsoft.AspNetCore.Http;
using Microsoft.Data.SqlClient;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Storage;
using TrainingReminderSystem.Dal;
using TrainingReminderSystem.Model;

namespace TrainingReminderSystem.Bll
{
    /// <summary>
    /// 岗位角色表逻辑层
    /// </summary>
    public partial class SysRolePostBll : PcLoginedBll
    {
        #region 添加和编辑的时候 验证数据和设置默认值

        /// <summary>
        /// 添加和编辑的时候 验证数据和设置默认值
        /// </summary>
        /// <param name="db"></param>
        /// <param name="model"></param>
        /// <param name="isAdd">添加还是编辑,可以不管此参数</param>
        /// <returns>是否通过,true表示验证通过,false代表验证没有通过</returns>
        public AjaxResult<dynamic> Validate(DbEntities db, SysRolePost model, bool isAdd)
        {
            var r = new AjaxResult<dynamic>();
            if (model == null)
            {
                r.Message = LanguageHelper.NoSubmitData;
                return r;
            }
            model.SysRolePostName = model.SysRolePostName.ExTrim();
            if (string.IsNullOrEmpty(model.SysRolePostName))
            {
                r.Message = "请输入岗位角色名称!";
                return r;
            }
            model.PY = ToolHelper.GetPy(model.SysRolePostName);

            model.SysRolePostPowerRelation = null;
            if (model.SysPowerIDs != null && model.SysPowerIDs.Count > 0)
            {
                model.SysRolePostPowerRelation = new List<SysRolePostPowerRelation>();
                foreach (var item in model.SysPowerIDs)
                {
                    SysRolePostPowerRelation relation = new SysRolePostPowerRelation();
                    relation.CreateDate = DateTime.Now;
                    relation.CreateSysEmployeeID = CurrentEmployee.SysEmployeeID;
                    relation.SysPowerID = item;
                    relation.SysRolePostID = model.SysRolePostID;

                    model.SysRolePostPowerRelation.Add(relation);
                }
            }

            var currentEmployee = CurrentEmployee;
            if (currentEmployee != null)
            {
                model.UpdateSysEmployeeID = currentEmployee.SysEmployeeID;
            }
            model.UpdateDate = DateTime.Now;
            model.SysStoreID = CurrentStore.SysStoreID;
            r.Success = true;
            return r;
        }

        #endregion

        #region 分页方法

        /// <summary>
        /// 查询条件,能替换掉一些属性查询为自定义查询
        /// </summary>
        /// <param name="where"></param>
        /// <param name="key"></param>
        /// <param name="val"></param>
        /// <returns></returns>
        private Expression<Func<SysRolePost, bool>> InitSearchDelegete(Expression<Func<SysRolePost, bool>> where,
            string key, string val)
        {
            //if (key == "SysRolePostID")
            //{
            //    int tempID = val.ExToInt32();
            //    return where.ExAnd(m => m.SysRolePostID == tempID);
            //}

            return null;
        }

        /// <summary>
        /// 分页方法
        /// </summary>
        /// <param name="index"></param>
        /// <param name="size"></param>
        /// <param name="form"></param>
        /// <param name="sortField"></param>
        /// <param name="asc"></param>
        /// <returns></returns>
        public AjaxResult<dynamic> GetListByPage(int index, int size, IFormCollection form = null, string sortField = "", bool asc = false)
        {
            using (var db = Db)
            {
                Expression<Func<SysRolePost, bool>> where = InitSearch<SysRolePost>(form, InitSearchDelegete); //拼接查询条件方法
                if (CurrentStore != null)
                {
                    int storeID = CurrentStore.SysStoreID;
                    var storeIDList = GetAllStoreIDCache(storeID, db);
                    where = where.ExAnd(m => storeIDList.Contains(m.SysStoreID));
                }

                #region 拼接查询条件

                if (form != null)
                {
                }

                #endregion

                int counts;
                var tempIDList = db.SysRolePost.ExOrderBy(sortField, asc).ExGetListByPage(index, size, out counts, where).Select(m => m.SysRolePostID);
                var result = new AjaxResult<dynamic>() { Success = true };
                result.Total = counts;
                IQueryable<SysRolePost> list = db.SysRolePost.Where(m => tempIDList.Contains(m.SysRolePostID)).ExOrderBy(sortField, asc);
                result.Result = list.Select(m => new
                {
                    SysRolePostID = m.SysRolePostID,
                    SysRolePostName = m.SysRolePostName,
                    PY = m.PY,
                    IsDel = m.IsDel,
                    UpdateEmployeeID = m.UpdateSysEmployeeID,
                    UpdateDate = m.UpdateDate,
                    Remark = m.Remark,

                    SysPowerIDs = m.SysRolePostPowerRelation.Select(n => n.SysPowerID),

                    m.SysStore.SysStoreName
                }).ToList();
                return result;
            }
        }

        #endregion

        #region 得到单对象,返回值有可能为null

        /// <summary>
        /// 得到单对象,返回值有可能为null
        /// </summary>
        /// <param name="id">主键值</param>
        /// <returns></returns>
        public SysRolePost GetModel(int id)
        {
            using (var db = Db)
            {
                return db.SysRolePost.FirstOrDefault(m => m.SysRolePostID == id);
            }
        }

        #endregion

        #region 保存数据

        /// <summary>
        /// 保存数据
        /// </summary>
        /// <param name="model">保存的对象,成功之后model对象的SysRolePostID能得到SysRolePostID</param>
        /// <returns></returns>
        public AjaxResult<dynamic> Save(SysRolePost model)
        {
            using (var db = Db)
            {
                if (model.SysRolePostID <= 0)
                {
                    return this.Add(model, db);
                }
                return this.Update(model, db);
            }
        }

        #endregion

        #region 添加数据

        /// <summary>
        /// 添加数据
        /// </summary>
        /// <param name="model">添加的对象,成功之后model对象的SysRolePostID能得到SysRolePostID</param>
        /// <returns></returns>
        public AjaxResult<dynamic> Add(SysRolePost model)
        {
            using (var db = Db)
            {
                return this.Add(model, db);
            }
        }

        /// <summary>
        /// 添加数据
        /// </summary>
        /// <param name="model">添加的对象,成功之后model对象的SysRolePostID能得到SysRolePostID</param>
        /// <param name="db"></param>
        /// <returns></returns>
        internal AjaxResult<dynamic> Add(SysRolePost model, DbEntities db)
        {
            var r = new AjaxResult<dynamic>() { Success = false };
            if (db == null) db = Db;
            var tempAr = Validate(db, model, true);
            if (tempAr.Success == false)
            {
                r.Message = tempAr.Message;
                r.Result = tempAr.Result;
                r.Total = tempAr.Total;
                return r;
            }
            IDbContextTransaction tran = db.Database.CurrentTransaction;
            bool hasTran = tran != null;
            if (hasTran == false) tran = db.Database.BeginTransaction();
            try
            {
                List<SysRolePostPowerRelation> relation = new List<SysRolePostPowerRelation>();
                if (model.SysRolePostPowerRelation != null)
                {
                    relation = model.SysRolePostPowerRelation;
                    model.SysRolePostPowerRelation = null;
                }
                db.SysRolePost.Add(model);
                db.SaveChanges();
                foreach (var item in relation)
                {
                    item.SysRolePostID = model.SysRolePostID;
                }

                db.SysRolePostPowerRelation.AddRange(relation);
                string error = AddLog(db, model, EnumLogType.新建);
                if (!string.IsNullOrEmpty(error))
                {
                    return AjaxResult<dynamic>.ErrorResult(error);
                }
                bool isSuccess = db.SaveChanges() >= 0;
                if (hasTran == false)
                {
                    tran.Commit();
                    tran.Dispose();
                    tran = null;
                }
                r.Success = isSuccess;
                r.Message = isSuccess ? "添加成功" : "添加失败,请重试!";
                r.Result = model.SysRolePostID;
                return r;
            }
            catch (Exception ex)
            {
                ex.ExLogError(GetCurrentOther());
                r.Total = (int)EnumTotal.异常;
                r.Success = false;
                r.Message = string.Format(LanguageHelper.Fail1, ex.ExMessageWithInner());
                return r;
            }
            finally
            {
                if (hasTran == false && tran != null) tran.Rollback();
            }
        }

        #endregion

        #region 编辑

        /// <summary>
        /// 编辑
        /// </summary>
        /// <param name="model">添加的对象,成功之后model对象的SysRolePostID能得到SysRolePostID</param>
        /// <returns></returns>
        public AjaxResult<dynamic> Update(SysRolePost model)
        {
            using (var db = Db)
            {
                return this.Update(model, db);
            }
        }

        /// <summary>
        /// 编辑
        /// </summary>
        /// <param name="model">添加的对象,成功之后model对象的SysRolePostID能得到SysRolePostID</param>
        /// <param name="db"></param>
        /// <returns></returns>
        internal AjaxResult<dynamic> Update(SysRolePost model, DbEntities db)
        {
            if (CurrentEmployee != null && CurrentEmployee.IsDemo)
            {
                return AjaxResult<dynamic>.ErrorResult("试用帐号不能更改角色权限");
            }
            var r = new AjaxResult<dynamic>() { Success = false };
            if (db == null) db = Db;
            var tempAr = Validate(db, model, false);
            if (tempAr.Success == false)
            {
                r.Message = tempAr.Message;
                r.Result = tempAr.Result;
                r.Total = tempAr.Total;
                return r;
            }
            IDbContextTransaction tran = db.Database.CurrentTransaction;
            bool hasTran = tran != null;
            if (hasTran == false) tran = db.Database.BeginTransaction();
            try
            {
                var beforeModel = db.SysRolePost.FirstOrDefault(m => m.SysRolePostID == model.SysRolePostID);
                if (beforeModel == null)
                {
                    r.Message = LanguageHelper.NoData;
                    return r;
                }
                beforeModel.SysRolePostID = model.SysRolePostID;
                beforeModel.SysRolePostName = model.SysRolePostName;
                beforeModel.PY = model.PY;
                beforeModel.UpdateSysEmployeeID = model.UpdateSysEmployeeID;
                beforeModel.UpdateDate = model.UpdateDate;
                beforeModel.Remark = model.Remark;
                //beforeModel.IsDel = model.IsDel;
                //beforeModel.SysRolePostEmployeeRelation = model.SysRolePostEmployeeRelation;
                //beforeModel.SysRolePostPowerRelation = model.SysRolePostPowerRelation;

                string error = AddLog(db, model, EnumLogType.编辑);
                if (!string.IsNullOrEmpty(error))
                {
                    return AjaxResult<dynamic>.ErrorResult(error);
                }
                var isSuccess = db.SaveChanges() >= 0;

                db.Database.ExExecuteSqlCommand(
                    $"delete from {typeof(SysRolePostPowerRelation).Name} where SysRolePostID={beforeModel.SysRolePostID}");
                if (model.SysRolePostPowerRelation != null && model.SysRolePostPowerRelation.Count > 0)
                {
                    //db.BulkInsert(model.SysRolePostPowerRelation);
                    db.SysRolePostPowerRelation.AddRange(model.SysRolePostPowerRelation);//EFCore超过3条,也会自动批量
                }

                db.SaveChanges();
                if (hasTran == false)
                {
                    tran.Commit();
                    tran.Dispose();
                    tran = null;
                }

                r.Total = (int)EnumTotal.用户信息及权限重新加载;
                r.Success = isSuccess;
                r.Message = isSuccess ? "编辑成功" : "编辑失败,请重试!";
                r.Result = model.SysRolePostID;
                return r;
            }
            catch (Exception ex)
            {
                ex.ExLogError(GetCurrentOther());
                r.Total = (int)EnumTotal.异常;
                r.Success = false;
                r.Message = "编辑失败:" + ex.ExMessageWithInner();
                return r;
            }
            finally
            {
                if (hasTran == false && tran != null) tran.Rollback();
            }
        }

        #endregion

        #region 删除

        /// <summary>
        /// 删除
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public AjaxResult<dynamic> Del(int id)
        {
            using (var db = Db)
            {
                return Del(id, db);
            }
        }

        /// <summary>
        /// 删除
        /// </summary>
        /// <param name="id"></param>
        /// <param name="db"></param>
        /// <returns></returns>
        internal AjaxResult<dynamic> Del(int id, DbEntities db)
        {
            var r = new AjaxResult<dynamic>() { Success = false };
            if (db == null) db = Db;
            IDbContextTransaction tran = db.Database.CurrentTransaction;
            bool hasTran = tran != null;
            if (hasTran == false) tran = db.Database.BeginTransaction();
            try
            {
                var beforeModel = db.SysRolePost.FirstOrDefault(m => m.SysRolePostID == id);
                if (beforeModel == null)
                {
                    r.Message = LanguageHelper.NoData;
                    return r;
                }
                beforeModel.IsDel = true;
                string error = AddLog(db, new SysRolePost() { SysRolePostID = id }, EnumLogType.删除);
                if (!string.IsNullOrEmpty(error))
                {
                    return AjaxResult<dynamic>.ErrorResult(error);
                }
                var isSuccess = db.SaveChanges() >= 0;
                if (hasTran == false)
                {
                    tran.Commit();
                    tran.Dispose();
                    tran = null;
                }
                r.Success = isSuccess;
                r.Message = isSuccess ? "删除成功" : "删除失败,请重试!";
                return r;
            }
            finally
            {
                if (hasTran == false && tran != null)
                {
                    tran.Rollback();
                    tran.Dispose();
                }
            }
        }

        #endregion
    }
}
